package br.com.lumis.saas.service.consumerclient;

import java.io.File;
import java.io.IOException;
import java.io.Writer;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.jsp.PageContext;

import lumis.portal.PortalException;
import lumis.portal.controller.ControllerException;
import lumis.portal.serviceinterfaceinstance.ServiceInterfaceInstanceControllerHtml;
import lumis.util.log.ILogger;
import lumis.util.log.LoggerFactory;
import br.com.lumis.saas.util.Configuration;

public class ConsoleController extends ServiceInterfaceInstanceControllerHtml {
	protected Writer out = null;
	private static final ILogger LOGGER = LoggerFactory
			.getLogger(ConsoleController.class);

	public ConsoleController(HttpServletRequest request,
			HttpServletResponse response, PageContext pageContext)
			throws ControllerException, PortalException {
		super(request, response, pageContext);

		try {
			out = response.getWriter();
		} catch (IOException e) {
			LOGGER.error(e);
		}
	}

	public void handleRequest() {
		
		Configuration config =  Configuration.getInstance();
		
		String hostname =  config.getProperty("saas.chef.hostname");
		String username = "ec2-user";

		File keyfile = new File(config.getProperty(
				"saas.path.document")); // or "~/.ssh/id_dsa"
		LOGGER
				.info("saas.path.document : "
						+ Configuration.getInstance().getProperty(
								"saas.path.document"));

		String keyfilePass = ""; // will be ignored if not needed

		try {
			
			

			out.write("<!DOCTYPE html>");
			out.write("<meta charset=\"utf-8\" />");
			out.write("<title>WebSocket Test</title>");
			out.write("<script language=\"javascript\" type=\"text/javascript\">");
			out.write("var wsUri = \"ws://ec2-23-23-235-241.compute-1.amazonaws.com:8001/tail/\";");
			out.write("var output;");
			out.write("function init()");
			out.write("{");
			out.write("output = document.getElementById(\"output\");");
			out.write("testWebSocket();");
			out.write("}");

			out.write("function testWebSocket()");
			out.write("{");
			out.write("websocket = new WebSocket(wsUri);");
			out.write("websocket.onopen = function(evt) { onOpen(evt) };");
			out.write("websocket.onclose = function(evt) { onClose(evt) };");
			out.write("websocket.onmessage = function(evt) { onMessage(evt) };");
			out.write("websocket.onerror = function(evt) { onError(evt) };");
			out.write("}");
			out.write("");
			out.write("function onOpen(evt)");
			out.write("{");
			out.write("writeToScreen(\"CONNECTED\");");
			out.write("doSend(\"WebSocket rocks\");");
			out.write("}");
			
			out.write("function onClose(evt)");
			out.write("{");
			out.write("writeToScreen(\"DISCONNECTED\");");
			out.write("}");			
			out.write("  function onMessage(evt)");
			out.write("{");			   
			out.write("var data = $.parseJSON(evt.data);");
			out.write("alert(data);");
			out.write("writeToScreen('<span style=\"color: blue;\">' + data[0] + ' '+ data[1]'</span>');");			
			out.write("}");
			
			out.write("function onError(evt)");
			out.write("{");
			out.write("writeToScreen('<span style=\"color: red;\">ERROR:</span> ' + evt.data);");
			out.write("}");
			out.write("");
			out.write("function doSend(message)");
			out.write("{");
			out.write("writeToScreen(\"SENT: \" + message);"); 
			out.write("websocket.send(message);");
			out.write("}");
			out.write("");
			out.write("function writeToScreen(message)");
			out.write("{");
			out.write("var pre = document.createElement(\"p\");");
			out.write("pre.style.wordWrap = \"break-word\";");
			out.write("pre.innerHTML = message;");
			out.write("output.appendChild(pre);");
			out.write("}");			
			out.write("  window.addEventListener(\"load\", init, false);");			
			out.write("</script>");																																																																	
			out.write("<h2>WebSocket Test</h2>");
			out.write("<div id=\"output\"></div>");
			out.write("</html> ");
			
			
			/* Create a connection instance */

		/*	Connection conn = new Connection(hostname);
			conn.connect();

			

			boolean isAuthenticated = conn.authenticateWithPublicKey(username,
					keyfile, keyfilePass);

			if (isAuthenticated == false)
				throw new IOException("Authentication failed.");

			

			Session sess = conn.openSession();

			sess.execCommand("tail -100f /home/ec2-user/saas/nohup.out");

			InputStream stdout = new StreamGobbler(sess.getStdout());

			BufferedReader br = new BufferedReader(
					new InputStreamReader(stdout));

			while (true) {
				String line = br.readLine();
				if (line == null)
					break;
				out.write(line + " <br/>");
				out.flush();

			}
			sess.close();

			conn.close();*/
			out.write("</body></html>");

		} catch (IOException e) {
			LOGGER.error("Erro ao conectar na maquina do chef.", e);
		}
	}
}
